<template>
  <div class="page-table table-page-container" :class="className">
    <!-- 显示表格 -->
    <el-table
      ref="table"
      :size="tableSize"
      v-loading="listInfo.loading"
      :max-height="listInfo.tableHeight || undefined"
      :data="data"
      border
      :style="tableStyle"
      @select-all="handleSelectionChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        v-if="checkBox"
        :key="'selection'"
        type="selection"
        width="55"
      />
      <el-table-column
        v-if="tabIndex"
        :key="'index'"
        align="center"
        label="序号"
        :width="fieldList.length === 0 ? '' : 80"
        fixed
      >
        <template v-slot="scope">
          <span>{{ scope.$index + 1 + (listInfo.query.pageNumber - 1) * listInfo.query.pageSize }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in fieldList.filter(item => !item.hidden)"
        :key="index"
        :prop="item.value"
        :label="item.label"
        :fixed="item.fixed"
        align="center"
        :width="item.width"
        :min-width="item.minWidth || '100px'"
      >
        <template v-slot="scope">
          <!-- solt 自定义列-->
          <template v-if="item.type === 'slot'">
            <slot
              :name="'col-' + item.value"
              :row="scope.row"
              :data="item"
            />
          </template>
          <!-- 嵌套表格 -->
          <template v-else-if="item.children">
            <el-table-column
              v-for="(childItem, childIndex) in item.children"
              :key="childIndex"
              :prop="childItem.value"
              :label="childItem.label"
              align="center"
              :width="item.width"
              :min-width="item.minWidth || '85px'"
            />
          </template>
          <!-- 标签 -->
          <el-tag v-else-if="item.type === 'tag'">
            {{ scope.row[item.value] }}
          </el-tag>
          <!-- 图片 -->
          <img
            v-else-if="item.type === 'image' && scope.row[item.value]"
            v-imgAlart
            height="50px"
            :src="scope.row[item.value]"
          >
          <!-- 时间 -->
          <span v-else-if="item.type === 'time'">
            {{ scope.row[item.value] ? formatDate(scope.row[item.value], 'yyyy-MM-dd hh:mm:ss') : '-' }}
          </span>
          <!-- 其他 -->
          <span v-else
            :style="{'color': getDataNameColor({dataList: listTypeInfo[item.list], value: 'value', label: 'key', data: scope.row[item.value]}) || ''}"
          >
            {{ getDataName({dataList: listTypeInfo[item.list], value: 'value', label: 'key', data: scope.row[item.value]}) || (scope.row[item.value] === 0 ? '0' : '-') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="handle && Object.keys(handle).length !== 0"
        :key="'handle'"
        :fixed="handle.fixed"
        align="center"
        :label="handle.label"
        :width="handle.width"
      >
        <template v-slot="scope">
          <template v-for="(item, index) in handle.btList">
            <!-- 自定义操作类型 -->
            <slot
              v-if="item.slot"
              :name="'bt-' + item.event"
              :data="{item, row: scope.row}"
            />
            <!-- 操作按钮 -->
            <!--
              :icon="item.icon" -->
            <el-button
              v-if="!item.slot && item.show && (!item.ifRender || item.ifRender(scope.row))"
              :key="index"
              v-waves
              size="mini"
              :type="item.type"
              :disabled="item.disabled || (item.ifDisabled && item.ifDisabled(scope.row))"
              :loading="scope.row[item.loading]"
              @click="handleClick(item.event, scope.row)"
            >
              <svg-icons v-if="item.type === 'svg'" :iconClass="item.icon" />
              <i v-else :class="item.icon"></i>
              {{ item.label }}
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <template v-if="pager">
      <div
        v-show="!listInfo.loading"
        class="pagination-container"
      >
        <el-pagination
          :current-page.sync="listInfo.query.pageNumber"
          :page-sizes="listInfo.pageSizes"
          :page-size="listInfo.query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="listInfo.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          popper-class="pagination-drop-container"
        />
      </div>
    </template>
  </div>
</template>

<script>
import { getDataName, getDataNameColor, formatDate } from '@/utils/index';
import Waves from '@/components/waves/waves';

export default {
  name: 'PageTable',
  directives: { Waves },
  props: {
    /* 表格通用大小 */
    tableSize: { type: String, default: 'small'},
    /* 自定义类名 */
    className: { type: String, default: '' },
    /* table style */
    tableStyle: { type: Object, default: () => { return { 'width': '100%'} } },
    /* 刷新 */
    refresh: { type: Number },
    /* 获取数据的接口 */
    // api: {type: Function},
    // api: { type: Object, default: () => { return {} } },
    api: [Object,  Function],
    /* 是否显示序号 */
    tabIndex: { type: Boolean, default: false },
    /* 是否有选择框 */
    checkBox: { type: Boolean, default: false },
    /* 选中列表 */
    checkedList: { type: Array, default: () => { return [] } },
    /* 类型列表 */
    listTypeInfo: { type: Object, default: () => { return {} } },
    /* 表格字段配置 */
    fieldList: { type: Array, default: () => { return [] } },
    /* 操作栏配置 */
    handle: { type: Object },
    /* 是否分页 */
    pager: { type: Boolean, default: true },
    /* 重置当前页 */
    initCurpage: { type: Number },
    /* 查询条件 */
    query: { type: Object, default: () => { return {} } },
    /* 列表数据 */
    data: { type: Array, default: () => { return [] } },
    /* 监听高度 */
    listenHeight: { type: Boolean, default: true },
    /* 用于测试的数据 */
    testTableRes: { type: Object, default: () => { return {} } }
  },
  data () {
    return {
      getDataName,
      getDataNameColor,
      formatDate,
      /* 列表相关 */
      listInfo: {
        tableHeight: 0, // 表格最大高度
        total: 0, // 总条数
        loading: false, // 加载动画
        pageSizes: [5, 10, 20, 50], // 分页数量列表
        query: { // 查询条件
          pageNumber: 1, // 当前页
          pageSize: 20 // 每页条数
        }
      }
    }
  },
  computed: {
    // ...mapGetters(['lang'])
  },
  watch: {
    initCurpage () {
      this.listInfo.query.pageNumber = 1
    },
    refresh () {
      if (!this.api) return;
      this.getList(this.api)
    }
  },
  methods: {
    /* 处理参数 */
    handleParams () {
      const obj = {}
      for (const key in this.query) {
        if (this.query[key] || this.query[key] === 0) {
          obj[key] = this.query[key]
        }
      }
      // 如果不需要分页，则无分页相关参数
      return this.pager ? { ...this.listInfo.query, ...obj } : obj
    },
    /* 得到数据 */
    getList (api) {
      this.listInfo.loading = true;
      // 每次调用接口时都自动绑定最新的数据
      if (typeof api === 'function') {
        api(this.handleParams()).then(res => {
          this.listInfo.loading = false;
          if (res.status === 200) {
            this.renderTableData(res)
          } else {
            this.$message({
              showClose: true,
              message: res.message || res.msg,
              type: 'error',
              duration: 3500
            })
          }
        }).catch(error => {
          this.$message.error(error);
          this.listInfo.loading = false
        })
      } else {
        this.$http(api, this.handleParams()).then(res => {
          this.listInfo.loading = false
          if (res.status === 200) {
            this.renderTableData(res)
          } else {
            this.$message({
              showClose: true,
              message: res.message || res.msg,
              type: 'error',
              duration: 3500
            })
          }
        }).catch(error => {
          this.$message.error(error)
          this.listInfo.loading = false
        })
      }
    },
    /* 获得列表数据之后渲染数据 */
    renderTableData (res) {
      res = res.body;
      let rows = [];
      if (res.rows && Array.isArray(res.rows)) {
        rows = res.rows;
      } else if (res.list && Array.isArray(res.list)) {
        rows = res.list;
      } else if (res.data && Array.isArray(res.data)) {
        rows = res.data;
      }

      if (rows) {
        // 使外面可以访问到表格数据
        const arr = Array.isArray(rows) ? rows : [];
        this.$emit('update:data', arr);
        if (this.pager) {
          this.listInfo.total = res.total
          // this.listInfo.query.pageNumber = res.content.pageNumber - 0
          // this.listInfo.query.pageSize = res.content.pageSize - 0
        }
        // 设置当前选中项
        this.checkedList.forEach(selected => {
          const row = arr.find(item => {
            return item.id === selected
          });
          this.$nextTick(() => {
            if (!row) return;
            this.$refs.table.toggleRowSelection(row, true)
          })
        });
        this.$emit('handleEvent', 'list', arr)
      } else if (res.data) {
        let arr = [];
        arr.push(res.data || {});
        this.$emit('handleEvent', 'dataList', arr)
      }
    },
    handleSizeChange (val) {
      const query = this.listInfo.query
      query.pageSize = val // 每页条数
      query.pageNumber = 1 // 每页条数切换，重置当前页
      this.getList(this.api)
    },
    handleCurrentChange (val) {
      this.listInfo.query.pageNumber = val // 当前页
      this.getList(this.api)
    },
    /* 派发按钮点击事件 */
    handleClick (event, data) {
      this.$emit('handleClick', event, data)
    },
    /* 选中数据 */
    handleSelectionChange (rows) {
      this.$emit('handleEvent', 'tableCheck', rows)
    }
  }
}
</script>

<style lang="scss">
/* 自定义表格相关 */
.table-page-container{
  .pagination-container{
    padding: 15px 0;
    text-align: right;
  }
}
  .pagination-drop-container .el-scrollbar__wrap {
    margin-bottom: -5px !important;
  }
</style>
